<?php
/**
 * Controller for ajax requests
 *
 */

class AjaxController extends Controller {
	
	/**
	 * Search leksem by name
	 * 
	 * @return json
	 */
	public function searchAction() {
		$leksName = $this->_request->getString('name');
		$currLang = strtolower($this->_request->getString('lang'));
		$dictionary = new Dictionary();
		$dictionary->loadByName($currLang);
		$websiteId = $this->_session->getInt('websiteId');
		$leks = $this->_model->findLeks($leksName, $websiteId);
		$preparedLeks = array();
		if(!empty($currLang) && $currLang != 'all') {
			foreach ($leks as $leksem) {
				$leksem->setTranslated($leksem->isTranslatedInto($dictionary->id));
                $preparedLeks[] = $leksem;
			}
		}
		else {
			$preparedLeks = $leks;
		}
		echo json_encode($preparedLeks);
	}
	
	/**
	 * Search leksem by original value
	 * 
	 * @return json
	 */
	public function searchvalAction() {
		$leksVal = $this->_request->getString('value');
		$currLang = strtolower($this->_request->getString('lang'));
		$dictionary = new Dictionary();
		$dictionary->loadByName($currLang);
		$websiteId = $this->_session->getInt('websiteId');
		$leks = $this->_model->findLeksByVal($leksVal, $websiteId);
		$preparedLeks = array();
		if(!empty($currLang) && $currLang != 'all') {
			foreach ($leks as $leksem) {
				$leksem->setTranslated($leksem->isTranslatedInto($dictionary->id));
                $preparedLeks[] = $leksem;
			}
		}
		else {
			$preparedLeks = $leks;
		}
		echo json_encode($preparedLeks);
	}
	
	public function indexAction() {
		//main action. we don't need it in this controller
	}
	
	/**
	 * Get leksem's trasnslation
	 * 
	 * @return string
	 */
	public function getTranslationAction() {
		$leksId = $this->_request->getInt('lid');
		$dictId = $this->_request->getInt('did');
		$translator = new Translator($dictId, $leksId);
		echo $translator->getTranslation();
	}
	
	/**
	 * Set current website 
	 * 
	 * @return string
	 */
	public function setCurrWebsiteAction() {
		$wsId = $this->_request->getInt('id');
		$website = new Website($wsId);
		if(!empty($wsId)) {
			$this->_session->set('websiteId', $website->id);
			$this->_session->set('websiteName', $website->name);
			echo "Current website: " . $website->name;
		}
	}
}